package com.cin.cma.client.config;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.cin.cma.common.constant.HeaderConstant;
import com.cin.cma.common.enums.SystemErrorCode;
import com.cin.cma.common.model.ApiErrorInfo;
import com.cin.cma.common.model.ApiResponse;
import com.cin.cma.common.signature.SignatureHelper;
import lombok.Builder;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Data
@Builder
public class OpenClient {
    private final Logger logger = LoggerFactory.getLogger(OpenClient.class);
    private OpenConfig config;

    /**
     * 执行请求
     *
     * @param uri  请求路径
     * @param body 请求参数
     * @return 执行结果
     */
    public ApiResponse<?> execute(String uri, Object body) {
        config.validate();
        String postUrl = this.config.getUri() + uri;
        String postBody = null;
        if (body != null) {
            postBody = JSONObject.toJSONString(body);
        }
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = IdUtil.fastSimpleUUID();
        String signature;
        try {
            signature = SignatureHelper.build(this.config.getSignKey(), this.config.getSignSecret(), "MD5", timestamp, nonce, postBody);
        } catch (Exception e) {
            logger.error("签名异常：url={} ,error={}", postUrl, e.getMessage());
            return ApiResponse.fail(new ApiErrorInfo(SystemErrorCode.NETWORK_ERROR, e.getMessage()));
        }
        HttpRequest httpRequest = HttpRequest.post(postUrl)
                .header(HeaderConstant.API_KEY, this.config.getSignKey())
                .header(HeaderConstant.SIGNATURE, signature)
                .header(HeaderConstant.TIMESTAMP, timestamp)
                .header(HeaderConstant.NONCE, nonce)
                .header(HeaderConstant.API_TYPE, "MD5");

        httpRequest.contentType(ContentType.JSON.getValue());
        httpRequest.body(postBody);
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        HttpResponse httpResponse;
        try {
            httpResponse = httpRequest.execute();
        } catch (Exception e) {
            logger.error("请求异常：url={} ,error={}", postUrl, e.getMessage());
            return ApiResponse.fail(new ApiErrorInfo(SystemErrorCode.NETWORK_ERROR, e.getMessage()));
        }
        String status = httpResponse.getStatus() + "";
        stopWatch.stop();
        String responseBody = httpResponse.body();

        //日志记录
//        String logInfo = StrUtil.format("请求地址：{}\r\n请求参数：{}\r\n请求耗时：{}\r\n返回状态：{}\r\n返回结果：{}",
//                postUrl, postBody, stopWatch.getTotalTimeMillis(), status, responseBody);
//        logger.info(logInfo);

        if (!"200".equals(status)) {
            return ApiResponse.fail(new ApiErrorInfo(SystemErrorCode.NETWORK_ERROR, "status=" + status));
        }
        return JSONObject.parseObject(responseBody, ApiResponse.class);
    }
}
